/**
 * Copyright 2015-2016 eyaomall.cn
 * All rights reserved.
 *
 * @project
 * @author pro
 * @version 1.0
 * @date 2016-03-07
 */
package com.eyaomall.wxmanage.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eyaomall.wxmanage.common.enums.CaptchaEnums;
import com.eyaomall.wxmanage.common.util.CaptchaUtil;
import com.github.bingoohuang.patchca.service.Captcha;
import com.lycheeframework.core.common.cookie.CookieManager;

/**
 * 验证码
 * 
 * @author pro
 *
 */
@Controller
public class CaptchaController {

	private static final Logger LOG = LoggerFactory.getLogger(CaptchaController.class);

	/**
	 * 验证码首页
	 * 
	 * @param response
	 * @param request
	 * @throws IOException
	 * @desc 此处必须为GET方法，retina.js会二次调用校验是否支持retina模式，找出验证码被刷新
	 */
	@RequestMapping("captcha")
	public void index(HttpServletResponse response, HttpServletRequest request) {
		response.setContentType("image/jpeg");
		response.setHeader("Cache-Control", "no-cache, no-store");
		response.setHeader("Pragma", "no-cache");
		long time = System.currentTimeMillis();
		response.setDateHeader("Last-Modified", time);
		response.setDateHeader("Date", time);
		response.setDateHeader("Expires", time);

		Captcha captcha = CaptchaUtil.getCaptcha();

		CookieManager cookieManager = new CookieManager(request,CaptchaEnums._CAPTCHA_FORM.getName());

		String code = captcha.getChallenge();
		
		cookieManager.setValue(CaptchaEnums._CAPTCHA_FORM.getName(), CaptchaEnums._CAPTCHA_CODE.getName(),code, true);
		cookieManager.save(response, CaptchaEnums._CAPTCHA_FORM.getName(), true);
		
		OutputStream output = null;
		try {
			output = response.getOutputStream();
			ImageIO.write(captcha.getImage(), "png", output);
			
			output.flush();
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
		}finally{
			if(output != null){
				try {
					output.close();
				} catch (IOException e) {
					//...
				}
				
			}
		}
	}
}
